package com.lmt.controller;

import com.lmt.entity.User;
import com.lmt.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Optional;

/**
 * 用户Controller
 * Date 2018/06/27
 *
 * @author MT-Lin
 */
@RestController
public class UserController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private final UserRepository userRepository;
    private String port;

    @Autowired
    public UserController(UserRepository userRepository, Environment environment) {
        this.userRepository = userRepository;
        this.port = environment.getProperty("server.port");
    }

    @GetMapping("/findUserById")
    public User findUserById(@RequestParam(name = "id") String id){
        Optional<User> optionalUser = userRepository.findById(id);
        logger.warn("provider->findUserById(PORT[{}]):{}", port, optionalUser.orElse(null));
        return optionalUser.orElse(null);
    }

    @PostMapping("/saveUser")
    public User saveUser(@RequestBody User user){
        User userSaved = userRepository.save(user);
        logger.warn("provider->saveUser:{}", userSaved);
        return userSaved;
    }

    @RequestMapping("/updateUser")
    public User updateUser(String id){
        Optional<User> optionalUser = userRepository.findById(id);
        logger.warn("provider->updateUser:{}", optionalUser.orElse(null));
        assert optionalUser.orElse(null) != null;
        optionalUser.orElse(null).setUserName("update");
        User update = userRepository.save(optionalUser.orElse(null));
        logger.warn("provider->updateUser:{}", update);
        return update;
    }

    @GetMapping("/getUserByRequestParam")
    public User getByRequestParam(String id, String username){
        return createUser(id, username);
    }

    @GetMapping("/getUserByMap")
    public User getByMap(String id, String username){
        return createUser(id, username);
    }

    @PostMapping("/getUserByEntity")
    public User getByMap(@RequestBody User user){
        user.setGmtCreate(new Date());
        user.setEmail(user.getUserName() + "@outlook.com");
        return user;
    }

    private User createUser(String id, String username) {
        User user = new User();
        user.setId(id);
        user.setUserName(username);
        user.setEmail(username + "@outlook.com");
        user.setGmtCreate(new Date());
        return user;
    }

}
